package src.D_WinSock;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

// 服务端
public class D02_TCP_Server {
    public static void main(String[] args) throws Exception {
        // 1、创建一个端口
        ServerSocket serverSocket = new ServerSocket(9999);
        // 2、接收客户端请求
        Socket socket = serverSocket.accept();
        // 3、使用字节流接收客户端传过来的东西
        InputStream is = socket.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(is);
        D02_TCP_Bean bean = (D02_TCP_Bean) ois.readObject();
        FileInputStream fis = new FileInputStream(bean.getImg()); // 拿到文件放到io流里准备读取
        FileOutputStream fos = new FileOutputStream("src\\D_WinSock\\1.png");
        byte[] bytes = new byte[1024];
        int b;
        while ((b = fis.read(bytes)) != -1){
            fos.write(bytes,0,b);
        }
        System.out.println("C端请求："+bean.getTxt());
        // 4、给客户端反馈是否收到
        OutputStream os = socket.getOutputStream();
        if (bean != null){
            os.write("收到".getBytes());
        }
        // 5、释放资源
        os.close();
        fos.close();
        fis.close();
        ois.close();
        is.close();
        socket.close();
        serverSocket.close();
    }

}
